
<html>


<div id="content">

<body>
  <script type="text/javascript" src="./lib/AjaxClass.js"> </script>
  <script type="text/javascript"> 

  
  // Create our class for querying the database to get the platform info.
  queryObject = function()
  {
  
    this.jsonObj = undefined;
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Function: OnSuccess
    // Usage: This function is the callback from our ajax class(AjaxClass.js) when the server responds to our query.
    //        We populate our Platform drop list with the data in the XML document that the server provides.
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    this.OnSuccess = function()
    {
      var rspText = this.GetResponseText();
      if( rspText != null )
      {
        // eval the object
        this.jsonObj = eval( '('+ rspText +')' )
        //var root = xmlobject.getElementsByTagName('platformList')[0];
        if( this.jsonObj != undefined )
        {
          // The JSON message is structured as follows:
          /*
            "platformList":{ 
            "platform":[
            {
            "name":"carocoops.CAP2.buoy",
            "desc":"CAROCOOPS CAP2, Capers Island Nearshore, SC",
            "url":"http://nautilus.baruch.sc.edu/carocoops_website/buoy_detail.php?buoy=buoy4",
            "obslist":{
              "observation name": "m_type_id",....
            }            
          */
          //var items = root.getElementsByTagName("platform");
          
          var urlPlatform = gup('platform');
          var urlPlatformNdx = -1;

          var PlatformCombo = document.getElementById( 'PlatformCombo' );
          var i;
          var platform = this.jsonObj.platformList.platform;
          for(i in platform )
          {
            var name = platform[i].name;
            if (name == urlPlatform) { urlPlatformNdx = i; }
            var Option = document.createElement( 'option' )
            if( typeof(platform[i].desc) != 'undefined' && platform[i].desc.length )
            {
              name = name + ' - ' + platform[i].desc;
            }
            Option.text = name;
            try
            {
              PlatformCombo.add(Option,null); // standards compliant
            }
            catch(ex)
            {
              PlatformCombo.add(Option); // IE only
            }          
          }
	  //remember to cast urlPlatformNdx as Number since returned as string from json objext
	  if (urlPlatformNdx != -1) { document.getElementById("PlatformCombo").selectedIndex = Number(urlPlatformNdx)+1;  }
	  myObject.enableObs();
        }
      }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Function: GetData
    // Usage: This function sends the request to the server for the json document containing the platforms and assocaited
    // Data.
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    this.GetData = function()
    {
      var strURL = '';
      strURL = './proxy-bin/AjaxProxy.php?url=http://neptune.baruch.sc.edu/xenia/rcoos/alerts/secoora.json'
      this.InitializeRequest('GET', strURL, true );
      this.Commit(null);
    }
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Function: enableObs
    // Usage: This is the callback function used when the user chooses a platform from the drop list. We lookup
    // the platform and determine which observations the user can set alerts for.
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    this.enableObs = function()
    {
      if( this.jsonObj != undefined )
      {
        //deleteParent();
        var Ndx=document.getElementById("PlatformCombo").selectedIndex;     
        if( Ndx > 0)
        {
          //Adjust the Ndx down one since the first entry in the drop list is the "Select Platform" entry.
          var platform = this.jsonObj.platformList.platform[Ndx-1];
 
          //Add a combo box per observation.
          var obsTable = document.getElementById("obsTable");
          
          resetTable(obsTable);
          var obsComboID = 0;
          for( obs in platform.obslist )
          {
            //var item = document.createElement("li"); 
            
            var rowCount = obsTable.rows.length; 
            var row = obsTable.insertRow(rowCount);

            //Add the check box.
            var col1 = row.insertCell(0);
            var andCheck=document.createElement("INPUT"); 
            andCheck.id = 'andcheckbox-' + obsComboID;
            andCheck.type = 'checkbox';
            andCheck.defaultChecked = false;
            col1.appendChild(andCheck);
            
            //Add the obs label.
            var col2 = row.insertCell(1);
            col2.innerHTML=obs;
            
            //Add the test selector, ">, <, =, >=, <="
            var col3 = row.insertCell(2);
            var tests = [">", "<", "==", ">=", "<="];
            var testCombo=document.createElement('select');
            testCombo.id = 'testcombo-' + obsComboID;
            var i;
            var len = tests.length;
            for(i=0; i < len; i++)
            {
              // Add some choices:
              var choice = document.createElement('option');
              choice.value = tests[i];
              choice.appendChild(document.createTextNode(tests[i]));
              testCombo.appendChild(choice);
            }
            col3.appendChild(testCombo);
            
            //Add the limits input box/
            var col4 = row.insertCell(3);
            var limit=document.createElement("INPUT"); 
            limit.id = 'limit-' + obsComboID;
            limit.setAttribute("limit","text");
            limit.setAttribute("size","5");
            //limit.setAttribute('style','float:none;display:inline;padding-left:10px;padding-right:20px;');
            col4.appendChild(limit);
            
            var col5 = row.insertCell(4);
            col5.innerHTML=platform.obslist[obs].uom;;

            obsComboID++;
          }
          document
        }
      }
    }
    resetTable = function(table)
    {
      while( table.hasChildNodes() )
      {
        table.removeChild(table.firstChild);
      }
    }

    deleteParent = function()
    {
      var obslist = document.getElementById("obsTable"); 
      for(var x = obslist.childNodes.length - 1; x >= 0; x--)
      {
        if( x > 0 )
        {
          var Node = obslist.childNodes[x];
          deleteChildren( Node );
          if (typeof Node.outerHTML !== 'undefined')
            Node.outerHTML = ''; //prevent pseudo-leak in IE
          else
            if(Node.parentNode) //if the node has a parent
              Node.parentNode.removeChild(Node); //remove the node from the DOM       
          delete( Node );
        }
      }
    }
    deleteChildren = function(node)
    {

      if(node) //make sure the node exists
      {
        for(var x = node.childNodes.length - 1; x >= 0; x--) //delete all of node's children
        {
          var childNode = node.childNodes[x];
          if(childNode.hasChildNodes()) //if the child node has children then delete them first
            deleteChildren(childNode);
          if (typeof childNode.outerHTML !== 'undefined')
            childNode.outerHTML = ''; //prevent pseudo-leak in IE
          else
            node.removeChild(childNode); //remove the child from the DOM tree
          delete childNode; //clean up just to be sure
        }
      }
    }
  }
  queryObject.prototype = new ajax();
  myObject = new queryObject();
  
  ////////////////////////////////////////////////////////////////////////////////////////////////
  // This is the ajax object we use to save the user inputted data.
  ////////////////////////////////////////////////////////////////////////////////////////////////
  saveObject = function()
  {
    this.OnSuccess = function()
    {
      document.body.style.cursor = 'default';    
    
      var strReturnString = this.GetResponseText();
      alert( strReturnString );
      var obsTable = document.getElementById("obsTable");     
      var rowCount = obsTable.rows.length; 
      for( var i = 0; i <  rowCount; i++ )
      {
        var row = obsTable.rows[i];
        //Get the check box cell.
        var chkbox = row.cells[0].childNodes[0]; 
        if( chkbox != undefined )
        {
          chkbox.checked = false;
          //Get the test operator cell.
          var operator = row.cells[2].childNodes[0]; 
          if(operator != undefined)
          {
            //Reset the test operator to '>'
            operator.options[0].selected = true;
          }
          var limit = row.cells[3].childNodes[0]; 
          if( limit != undefined )
          {
            limit.value = '';
          }
        }
      }
      /*else
      {
        alert( "Unable to process the alert." );
      }*/
    }

    this.SendData = function()
    {
      // Get the platform the user has selected.
      var Ndx=document.getElementById("PlatformCombo").selectedIndex;
      if( Ndx <= 0 )
      {
        return;
      }
      var strPlatform = document.getElementsByTagName("option")[Ndx].text;
      // The platform combo consists of: "platform handle - description" so we want to split that apart to get just the platfrom
      // handle.
      var aPlatformandName = strPlatform.split( '-', 2 );
      // Trim the lading/trailing whitespaces.
      strPlatform = aPlatformandName[0].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
      
      //var ParamList = 'PLATFORM=' + strPlatform;
      var xmlResponse = "<response><platform>" + escape(strPlatform) + "</platform>";
      
      
      var platform = myObject.jsonObj.platformList.platform[Ndx-1];

      var Email      = document.getElementById( 'email' ).value;      
      if( Email.length > 0 )
      {
        xmlResponse += "<email>" + escape(Email) + "</email>";
      }
      else
      {
        alert( "An email address must be provided to register for the alert." );
        return;
      }
      var ID = 0
      var  obsParams = '';
      //Go row by row in the table to see what observations the user has indicated they want to build an alert on.
      var obsTable = document.getElementById("obsTable"); 
      var rowCount = obsTable.rows.length; 
      for( var i = 0; i <  rowCount; i++ )
      {
        var row = obsTable.rows[i];
        //Get the check box cell.
        var chkbox = row.cells[0].childNodes[0]; 
        if( chkbox != undefined )
        {
          if( chkbox.checked )
          {
            var obsName = row.cells[1].innerHTML;
            if( obsName.length )
            {
              var operator = row.cells[2].childNodes[0]; 
              if(operator != undefined)
              {
                operator = operator.value;
                operator = this.quoteXML(operator);
                operator = escape(operator);
                if(operator == undefined)
                {
                  alert("Please choose a valid test operator.");
                  return;
                }
                var limit = row.cells[3].childNodes[0]; 
                if( limit != undefined )
                {
                  if(limit.value.length == 0)
                  {
                    alert("Observation checked, however no limit was entered to test against.");
                    return;
                  }
                  if( obsParams.length )
                  {
                    obsParams += "<cond>AND</cond></alert>";
                  }
                  obsParams += "<alert><id>" + escape(platform.obslist[obsName].m_type_id) + "</id><limit>" + escape(limit.value) + "</limit><uom>" + escape(platform.obslist[obsName].uom) + "</uom><operator>'" + operator + "'</operator>";
                }
                else
                {
                  alert("Observation checked, however no limit was entered to test against.");
                  return;
                }
              }
              else
              {
                alert("Please choose a valid test operator.");
                return;
              }
            }
          }
        }
      }
      if( obsParams.length )
      {
        obsParams += "</alert>";
        xmlResponse += "<alerts>" + obsParams + "</alerts>";
        xmlResponse = escape(xmlResponse);
        xmlResponse += "</response>";
        //this.InitializeRequest('POST', './cgi-bin/AjaxProxy.php?url=http://carocoops.org/~dramage_prod/cgi-bin/rcoos/SaveAlertInfoRev2.php', true );
        this.InitializeRequest('POST', './proxy-bin/AjaxProxy.php?url=http://neptune.baruch.sc.edu/rcoos/emailAlertHandler.py', true );
        this.SetRequestHeader("Content-Length", xmlResponse.length);
        this.SetRequestHeader("Connection", "close");      
        var outbuf = "operation=add&xml=" + xmlResponse;
        this.Commit( outbuf );
        //Change cursor to the wait cursor since the server mostly likely is not going to respond instantly.
        document.body.style.cursor = 'wait';    
      }
      else
      {
        alert("No observations checked for testing. Cannot add an alert.");
        return;
      }
    }
    this.quoteXML = function(operatorString)
    {
      var i;
      var outBuf = '';
      
      for(i = 0; i < operatorString.length; i++)
      {
        //DWR 9/10/2010 
        //Added use of the charAt() function instead of trying to reference characters via []. IE7 was erroring on that.
        var character = operatorString.charAt(i);
        switch(character)
        {
          case '<':
            character = '&lt;';
            break;
          case '>':
            character = '&gt;';
            break;
          default:
            break;           
        }
        outBuf += character;
      }
      return(outBuf);
    }
  }
  saveObject.prototype = new ajax();
  saveUserInput = new saveObject();

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Function: gup
    // Usage: get url parameters
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


</script>
  
<h1>Email Alerts</h1>
<h4>This form allows you to create a single alert or a combination of observations you would like to be alerted on.</br> 
First, choose a platform from the Platform dropdown list.</br>
Next, enter in the email address you want the alert sent to.</br>
Click the check box next to the observation or observations and enter the value for each observation to be exceeded.</br> 
For instance, from the Platform droplist choose "carocoops.CAP2.buoy - CAROCOOPS CAP2, Capers Island Nearshore, SC" </br>
Now click the box next to wind_from_direction and enter value of 100 degrees true and click the box next to wind_speed and enter value of 10 mph.</br>
You would then be alerted when wind_from_direction exceeds 100 degrees and wind_speed exceeds 10mph.  </h4>  
<!--
<form id="alertsForm" method="post" action="http://neptune.baruch.sc.edu/rcoos/testprog.py">
-->
<div id="alerts">
  <ul>
    <li><label for="PlatformCombo">Platform:</label>
      <select name="PlatformCombo" id="PlatformCombo" onchange="myObject.enableObs()">
            <option>Select Platform</option>			
          </select>
          <input type=HIDDEN id="platformurl" value="-1">
    </li>
    <li><label for="email">Email Address:</label>
      <input type="text" name="email" id="email" size="20">
    </li>
  </ul>
  <table id='obsTable'></table>
</div>
  

<div align="center"><br /><button type="button" onclick="saveUserInput.SendData()">Send</button>&nbsp;</div>
	
<p class="embiggen">Disclaimer: Data to be used at your own risk. These realtime data are considered provisional. Data obtained from the buoy are sent to via satellite to a receiving modem at the University of South Carolina. Data are then processed automatically for viewing on the Web. At no point have the data been reviewed or edited and thus errors from the buoy can and will be displayed online. Errors can occur due to a variety of reasons including biological fouling or physical damage to the sensors.</p>

<p>&nbsp;</p>

<script type="text/javascript">
    // Send the ajax query to get the platform list.
    myObject.GetData();    
</script>
</form>

</body>

</html>
